package com.example.demo.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity //开启安全配置
//内存认证方式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public JdbcTokenRepositoryImpl tokenRepository() {
        JdbcTokenRepositoryImpl jr = new JdbcTokenRepositoryImpl();
        jr.setDataSource(dataSource);
        return jr;
    }

    /**
     * 用户和角色的关系
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    DataSource dataSource;
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //userDetailService验证方式
        // Encoder  Decoder
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);


////jdbc验证方式
////        // Encoder  Decoder
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        String UserSQL = "select username,password,valid from t_customer where username=?";
//        String authoritiSql="select c.username, a.authority\n" +
//                "from t_customer c,\n" +
//                "     t_authority a,\n" +
//                "     t_customer_authority ac\n" +
//                "where  c.id=ac.customer_id and a.id=ac.authority_id and c.username=?";
//        auth.jdbcAuthentication().passwordEncoder(encoder)
//                .dataSource(dataSource)
//                .usersByUsernameQuery(UserSQL)
//                .authoritiesByUsernameQuery(authoritiSql);


        //  内存验证方式
//        auth.inMemoryAuthentication().passwordEncoder(encoder)
//                .withUser("shitou")
//                .password(encoder.encode("12345"))
//                //设定角色
//                .roles("common")
//                .and()
//                .withUser("lisi")
//                .password(encoder.encode("123456"))
//                .roles("vip");


    }

    /**
     * 角色和资源的关系
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //资源文件不要限制权限
        http.authorizeRequests()

                .antMatchers("/detail/common/**")
                .access("hasRole('common') or hasRole('vip')")
                .antMatchers("/detail/vip/**").hasRole("vip")
                .antMatchers("/login/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/")
                // .successForwardUrl("/") //默认是post提交
                //登录不要求验证 否则出现登录死循环
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/mylogout")  //必须和注销按钮的action值一致 而且 注销的方式必须是post
                .logoutSuccessUrl("/login")
                .and()
                .rememberMe().rememberMeParameter("rememberme")
                .tokenValiditySeconds(200)
                .tokenRepository(tokenRepository());
    }


}
